package com.qiange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiange.common.Result;
import com.qiange.dao.DishDao;
import com.qiange.dto.DishDto;
import com.qiange.pojo.Dish;
import com.qiange.pojo.DishFlavor;
import com.qiange.service.DishFlavorService;
import com.qiange.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithFlavor(DishDto dishDto) {
        save(dishDto);

        Long dishId = dishDto.getId();
        //System.out.println(dishId);

        List<DishFlavor> flavorList = dishDto.getFlavors();

        flavorList = flavorList.stream().map(i->{
            i.setDishId(dishId);
            return i;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavorList);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id){

        DishDto dishDto = new DishDto();

        //根据id查询菜品信息
        Dish dish = this.getById(id);

        BeanUtils.copyProperties(dish,dishDto);

        //根据菜品id查询口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper();
        lqw.eq(DishFlavor::getDishId,id);

        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);
        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);

        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);

        dishFlavorService.saveBatch(flavors);

    }
}
